import axios from 'axios'
import { BASE_URL } from './config.js'
import {demoModel} from '../demo/DemoModel'
/* global localHost */
// 区分生产环境和开发环境采用不同的baseURL
// const baseURL = process.env.NODE_ENV === 'development' ? '/api' : localHost
const baseURL = BASE_URL
// 创建axios实例
// axios.defaults.timeout = 10000
const service = axios.create({
  baseURL: baseURL, // api 的 base_url
  timeout: 60 * 1000, // 请求超时时间
})
var orgId = null
var orgNameArr = ['organizationid', 'organizationId', 'orgid', 'orgId']
var res1000011 = { code: 1000011, msg: '请求错误', data: [], info: [] }

// 遍历对象去掉前后空格
function displayProp(obj) {
  for (var key in obj) {
    if (typeof obj[key] === 'string') {
      obj[key] = obj[key].trim()
    } else if (typeof obj[key] === 'object') {
      displayProp(obj[key])
    }
    // 逐级查找对象里面的orgNameArr里面的key字段,当有对应值时将obj[key]赋值给全局定义的orgId
    if (orgNameArr.includes(key)) {
      orgId = obj[key]
    }
  }
}
// request拦截器
service.interceptors.request.use(
  config => {
    let token = demoModel.getToken()
    if(token){
      config.headers['Authorization'] = 'Bearer ' + token    
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug

    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  async response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data
    return response.data
  },
  async error => {
    console.dir(error)
    console.log('err->>>' + error) // for debug
    if (error.response) {
      if (error.response.status === 401) {
        return Promise.reject(error.response.msg || 'error')
      }
      const code = error.response.data.code
      if (code === 10022 || code === 10023 || code === 10025) {
        if (document.getElementsByClassName('el-message-box').length === 0 && window.location.href.indexOf('/login') < 0) {
          console.log('登录已过期')
        }
        return Promise.reject(error.response.msg || 'error')
      }
    }
    if (error.response.status === 403) {
      console.log('当前账号无权限进行当前操作')
      return Promise.reject('当前账号暂无权限进行当前操作' || error)
    }
    console.log(error.message)
    return Promise.reject(error)
  }
)

export default service
